package org.springblade.modules.mes.opcua.listener;

import lombok.extern.slf4j.Slf4j;
import org.springblade.core.tool.utils.ObjectUtil;
import org.springblade.modules.mes.opcua.constant.OpcUaError;
import org.springblade.modules.mes.opcua.constant.OpcUaKey;
import org.springblade.modules.mes.opcua.itf.OpcUa;
import org.springblade.modules.mes.opcua.server.*;
import org.springblade.modules.mes.opcua.vo.OpcUaVO;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class KeyChangeListener {

	@Resource
	private RequestService requestTaskService;
	@Resource
	private ScanService scanCodeService;
	@Resource
	private ArchiveService archiveService;
	@Resource
	private ParamService paramService;
	@Resource
	private ToolService toolService;

	public void onDataValueReceived(String key, Object value) {
		log.info(key + ":" + value);
		if (ObjectUtil.isEmpty(value)) {
			log.info(key + ":" + value + ":值为空");
			return;
		}
		OpcUaVO ctx = new OpcUaVO(key, value);
		try {
			if (key.contains("archive") && "1".equals(value.toString())) {
				//归档和强制归档
				archiveService.stationArchive(ctx);
			} else if (key.contains("scanStatus") && "1".equals(value.toString())) {
				//物料绑定
				scanCodeService.barcodeCheck(ctx);
			} else if (key.contains("orderStatus") && "1".equals(value.toString())) {
				//申请订单
				requestTaskService.assemblyBarcodeApply(ctx,null);
			} else if (key.contains("param") && "1".equals(value.toString())) {
				//物料绑定
				paramService.saveParam(ctx);
			} else {
				log.warn("unchecked:" + key + ":" + value);
			}
			OpcUa.getInstance().writeValue(ctx, null, OpcUaKey.act, "1");
		} catch (Exception e) {
			try {
				OpcUa.getInstance().writeValue(ctx, ctx.getPosition(), ctx.getActKey(), (short) 3);
				//系统异常
				toolService.plcMessage(ctx, OpcUaError.E90000);
			} catch (Exception ex) {
			}
			e.printStackTrace();
			log.error("处理PLC消息异常", e);
		}
	}
}
